const { mkPager } = require('../utils')
const { findLoanByLimitAndName, findLoanByLimit, getLoanCount,
  getLoanCountByName, insertLoan, updateLoanByfields,
  deleteLoanById, findLoanById } = require('../models/loan.js')
const { checkNulValueList } = require('./loanConfig')
const { checkNulValue } = require('../utils')
const { roles, ADMIN, INPUT } = require('./config.js')
const { stateFlow, waitingStatus,
  nonCommitStatus } = require('./approveHelper')
exports.loanList = async ctx => {
  // 获取查询字符串参数
  const { pageNo, pageSize, name } = ctx.query

  // 生成分页的Limit条件
  const { start, size } = mkPager(pageNo, pageSize)

  if (name) {
    var dataRes = await findLoanByLimitAndName(name, start, size)
    var countRes = await getLoanCountByName(name)
  } else {
    var dataRes = await findLoanByLimit(start, size)
    var countRes = await getLoanCount()
  }
  const { rows } = countRes[0];
  const pages = Math.ceil(rows / size)  // 100(总条数) / 30(一页显示多少条) === 4
  return ctx.success({
    data: {
      data: dataRes,
    },
    pages,// 能分成多少页--查出总条数再计算
    rows,// 总条数
    pageSize: size,
  })
}

// 创建贷款
exports.createLoan = async ctx => {
  // 先做权限判断
  if (type !== ADMIN && type !== INPUT) {
    return ctx.fail(`只有销售人员或者管理人员有权限录入！,${roles[type]}不能提交`)
  }
  // 获取请求体参数  ctx.request.body
  // 验证字段是否缺失
  const res = checkNulValue(ctx.request.body, checkNulValueList)
  if (!res.result) {
    return ctx.fail(`字段【${res.data.key}】值不正确，值为：${res.data.value}`)
  }
  // 向数据库插入一条数据
  const { id, type } = ctx.state.user
  const insertLoanRes = await insertLoan({ ...ctx.request.body, user_id: id, creator: roles[type] })
  if (insertLoanRes.affectedRows === 0) {
    return ctx.fail('创建申请失败！')
  }
  return ctx.success('创建申请成功!')
}

// 更新贷款
exports.updateLoan = async ctx => {
  // 先做权限判断
  const { type } = ctx.state.user;
  if (type !== ADMIN && type !== INPUT) {
    return ctx.fail(`只有销售人员或者管理人员有权限修改！,${roles[type]}不能提交`)
  }
  const reqRes = ctx.request.body;
  const id = reqRes.id;
  delete reqRes.id;
  const res = await updateLoanByfields(reqRes, id);
  if (res.affectedRows === 0) {
    return ctx.fail('修改失败')
  }
  return ctx.success('修改成功')
}

exports.deleteLoan = async ctx => {
  // 先做权限判断
  const { type } = ctx.state.user;
  if (type !== ADMIN && type !== INPUT) {
    return ctx.fail(`只有销售人员或者管理人员有权限修改！,${roles[type]}不能提交`)
  }
  const { delId } = ctx.params;
  const delRes = await deleteLoanById(delId);
  if (delRes.affectedRows === 0) {
    return ctx.fail('删除失败！')
  }
  return ctx.success('删除成功！')
}

exports.submitToApprove = async ctx => {
  // 获取请求体id，查询状态，从而使用链表进行获取下一个该有的状态
  const { id } = ctx.request.body;
  const loanRes = await findLoanById(id);
  if (loanRes.length === 0) {
    return ctx.fail('当前申请不存在')
  }
  // 获取当前状态
  const { status } = loanRes[0]
  // 判断当前状态是否可以进行下一步   1457wating
  if ([...waitingStatus, ...nonCommitStatus].includes(status)) {
    return ctx.fail(`当前流程不能继续提交：${status}`)
  }

  let currentStatus = stateFlow[status]
  currentStatus = currentStatus.pass || currentStatus

  // 更新当前状态
  if (status === currentStatus.v) {
    return ctx.fail('状态无法改变，状态相同')
  }

  const updateRes = await updateLoanByfields({ status: currentStatus.v }, id)
  if (updateRes.changedRows === 0) {
    return ctx.fail('更新状态失败')
  }

  // 响应状态的变更
  return ctx.success({
    info: '提交成功',
    from: status,
    to: currentStatus.v
  })
}

exports.queryLoan = async ctx => {
  const { id } = ctx.query;
  const res = await findLoanById(id)
  if (res.length === 0) {
    return ctx.fail('此申请不存在')
  }
  ctx.success({
    info: '查看成功',
    data: res[0]
  })
}